package work.parabola.keyboardswitch.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.parabola.keyboardswitch.common.ResponseCode;
import work.parabola.keyboardswitch.common.ServerResponse;
import work.parabola.keyboardswitch.dao.SwitchTypeDoMapper;
import work.parabola.keyboardswitch.pojo.query.switchtype.ListQuery;
import work.parabola.keyboardswitch.pojo.repository.SwitchTypeDo;
import work.parabola.keyboardswitch.pojo.vo.switchtype.SwitchTypeListVo;
import work.parabola.keyboardswitch.service.ISwitchTypeService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@Service
public class SwitchTypeServiceImpl implements ISwitchTypeService {

    @Autowired
    private SwitchTypeDoMapper switchTypeDoMapper;

    @Override
    public ServerResponse getSwitchTypeList(ListQuery listQuery) {
        if (listQuery == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<SwitchTypeDo> switchTypeDoList = this.switchTypeDoMapper.selectByParams(listQuery.getSearchWord());
        List<SwitchTypeListVo> switchTypeListVoList = new ArrayList<>();
        for (SwitchTypeDo switchTypeDo : switchTypeDoList) {
            SwitchTypeListVo vo = new SwitchTypeListVo();
            vo.setId(switchTypeDo.getId());
            vo.setName(switchTypeDo.getName());
            vo.setParentId(switchTypeDo.getParentId());
            switchTypeListVoList.add(vo);
        }
        return ServerResponse.createBySuccess(switchTypeListVoList);
    }

    @Override
    public List<Integer> getSwitchTypeListByParentId(Integer switchTypeId) {
        List<Integer> switchTypeList = new ArrayList<>();
        if (switchTypeId == null) {
            return switchTypeList;
        }

        Queue<Integer> queue = new LinkedList<>();
        queue.add(switchTypeId);
        while (!queue.isEmpty()) {
            Integer item = queue.poll();
            switchTypeList.add(item);
            List<Integer> list = this.switchTypeDoMapper.selectByParentId(item);
            list.forEach(listItem -> queue.add(listItem));
        }
        return switchTypeList;
    }
}
